package com.dlc.shop.distribution.common.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.util.PrincipalUtil;
import com.dlc.shop.distribution.common.constants.DistributionUserStateEnum;
import com.dlc.shop.distribution.common.dao.DistributionAuditingMapper;
import com.dlc.shop.distribution.common.dao.DistributionUserBindMapper;
import com.dlc.shop.distribution.common.dao.DistributionUserMapper;
import com.dlc.shop.distribution.common.dto.DistributionAuditingDto;
import com.dlc.shop.distribution.common.model.DistributionAuditing;
import com.dlc.shop.distribution.common.model.DistributionUser;
import com.dlc.shop.distribution.common.model.DistributionUserBind;
import com.dlc.shop.distribution.common.param.DistributionParam;
import com.dlc.shop.distribution.common.param.RangeTimeParam;
import com.dlc.shop.distribution.common.service.DistributionAuditingService;
import com.dlc.shop.distribution.common.service.DistributionBindUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lgh on 2019/04/01.
 */
@Service
@RequiredArgsConstructor
public class DistributionAuditingServiceImpl extends ServiceImpl<DistributionAuditingMapper, DistributionAuditing> implements DistributionAuditingService {

    private final DistributionAuditingMapper distributionAuditingMapper;

    private final DistributionUserMapper distributionUserMapper;
    private final DistributionUserBindMapper distributionUserBindMapper;
    private final DistributionBindUserService distributionBindUserService;

    @Override
    public Page<DistributionAuditingDto> distributionAuditingPage(Page page, DistributionAuditing distributionAuditing, RangeTimeParam rangeTimeParam, Integer startExpenseNumber, Integer endExpenseNumber, Double startPayAmount, Double endPayAmount, DistributionParam distributionParam) {
        Page<DistributionAuditingDto> auditingPage = distributionAuditingMapper.distributionAuditingPage(page, distributionAuditing, rangeTimeParam, startExpenseNumber, endExpenseNumber, startPayAmount, endPayAmount, distributionParam);
        for (DistributionAuditingDto record : auditingPage.getRecords()) {
            if(StrUtil.isNotBlank(record.getUserMobile())) {
                record.setUserMobile(PhoneUtil.hideBetween(record.getUserMobile()).toString());
            }
            if (PrincipalUtil.isMobile(record.getNickName())) {
                record.setNickName(PhoneUtil.hideBetween(record.getNickName()).toString());
            }
            Long parent = record.getParentDistributionUserId();
            if (Objects.nonNull(parent)) {
                if(StrUtil.isNotBlank(record.getParentUserMobile())) {
                    record.setParentUserMobile(PhoneUtil.hideBetween(record.getParentUserMobile()).toString());
                }
                if (PrincipalUtil.isMobile(record.getParentNickName())) {
                    record.setParentNickName(PhoneUtil.hideBetween(record.getParentNickName()).toString());
                }
            }
        }
        return auditingPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void examine(DistributionAuditing distributionAuditing) {
        DistributionUser distributionUser = new DistributionUser();
        distributionUser.setDistributionUserId(distributionAuditing.getDistributionUserId());
        distributionUser.setBindTime(new Date());
        distributionUser.setStateRecord(null);
        //判断是否通过
        if (distributionAuditing.getState() == 1) {
            DistributionUser distributionUserDb = distributionUserMapper.selectById(distributionAuditing.getDistributionUserId());
            if (Objects.isNull(distributionUserDb)) {
                throw new YamiShopBindException("yami.user.off");
            }
            // 如果之前是暂时封禁状态，现在改成正常状态,恢复以前的没有被抢的绑定用户。
            if (Objects.nonNull(distributionUserDb.getStateRecord()) && distributionUserDb.getStateRecord() == DistributionUserStateEnum.BAN.getValue()) {
                List<DistributionUserBind> userBindList = distributionUserBindMapper.selectList(new LambdaQueryWrapper<DistributionUserBind>()
                        .eq(DistributionUserBind::getDistributionUserId, distributionAuditing.getDistributionUserId())
                        .eq(DistributionUserBind::getState, -1)
                        .eq(DistributionUserBind::getInvalidReason, 3));
                if(CollectionUtil.isNotEmpty(userBindList)) {
                    // 查询出所有暂时封禁但已经被抢的用户
                    List<String> userIds = distributionUserBindMapper.selectClearUserByDistributionUserId(userBindList);
                    if(CollectionUtil.isNotEmpty(userIds)) {
                        userBindList = userBindList.stream().filter(userBind -> !userIds.contains(userBind.getUserId())).collect(Collectors.toList());
                    }
                    if(CollectionUtil.isNotEmpty(userBindList)) {
                        // 将没有被抢的，失效的绑定用户设为正常。
                        distributionUserBindMapper.recoveryRelationsByUserId(userBindList);
                    }
                }
            }
            distributionUser.setLevel(distributionUserDb.getLevel());

            if (distributionUserDb.getState() == DistributionUserStateEnum.FAIL_AUDIT.getValue() ||
                    distributionUserDb.getState() == DistributionUserStateEnum.WAIT_AUDIT.getValue()){
                //通过审核,修改分销员状态
                distributionUser.setState(1);
                // 邀请人绑定申请分销员
//                distributionBindUserService.bindUser(distributionAuditing.getParentDistributionUserId(), distributionAuditing.getDistributionUserId());
            }

        } else if (distributionAuditing.getState() == -1) {
            //未通过审核,修改分销员状态
            distributionUser.setState(3);
            distributionUser.setLevel(1);
        }
        distributionUserMapper.updateStatusById(distributionUser);
        distributionAuditingMapper.updateById(distributionAuditing);
    }
}
